<?php

namespace App\Http\Controllers\PartnerApi;

use App\Enums\AssetKeyStatus;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\AssetKey;
use App\Models\Product;

class AssetKeyController extends Controller
{
    /** 兑换码查询 */
    public function query()
    {
        request()->validate([
            'key' => 'required',
            'contract_address' => 'required',
        ]);

        $key = $this->findKeyOrFail(request()->contract_address, request()->key, request()->mobile);
        $product = Product::query()->where('contract_address', $key->asset->contract_address)->first();

        $arr = [
            'product_name' => $product->name,
            'product_logo' => $product->logo_url,
            'contract_address' => $key->asset->contract_address,
            'create_time' => $key->created_at->toDateTimeString(),
            'status' => $key->status->value,
        ];
        if ($key->status->is(AssetKeyStatus::USED())) {
            $arr['use_time'] = $key->use_time;
        }
        if ($key->prev_code) {
            $arr['prev_code'] = $key->prev_code;
        }

        return $arr;
    }

    /** 兑换码使用 */
    public function consume()
    {
        request()->validate([
            'key' => 'required',
            'contract_address' => 'required',
        ]);

        $key = $this->findKeyOrFail(request()->contract_address, request()->key, request()->mobile);
        if ($key->status->is(AssetKeyStatus::USED())) {
            throw new ApiException('兑换码已使用');
        }
        $key->status = AssetKeyStatus::USED();
        $key->use_time = now();
        $key->partner_id = request()->partner_id;
        $key->save();
    }

    private function findKeyOrFail($contractAddress, $key, $mobile)
    {
        $assetKey = AssetKey::query()
            ->whereHas('asset', function ($q) use ($contractAddress) {
                return $q->where('contract_address', $contractAddress);
            })->where('key', $key)->first();
        if (!$assetKey) {
            throw new ApiException('无效的兑换码');
        }
        $old_key = AssetKey::query()->where('prev_code', $key)->first();
        if ($old_key) {
            throw new ApiException('该兑换码已被转售！');
        }

        if (!$assetKey->asset) {
            throw new ApiException('兑换码对应的资产不存在');
        }

        if (!empty($mobile) && $assetKey->asset->user->mobile !== $mobile) {
            throw new ApiException('兑换码和手机号不匹配');
        }

        return $assetKey;
    }
}
